// 引入 react 依赖
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Text, View, Image, TouchableOpacity, ImageBackground, ScrollView, InteractionManager } from 'react-native';

// 引入第三方依赖
import _ from 'lodash';
import pureRender from 'pure-render-decorator';
import * as ActionTypes from '../../constants/constants.js'
import { Actions } from 'react-native-router-flux';

// antd 按需加载
import { Tabs, Toast, Portal, Modal } from '@ant-design/react-native';

// 引入 处理数据 所需文件
import { getOrderList, cancelOrder } from './module/module.js'
import { pay } from '../Pay/module/module.js'

// 引入样式
import Style from './style/style.js';

// 引入公用组件
import { Status, NavBar, RnFlatList, RnImage, IsPay } from '../../components/index.js'

// 引入专用组件
import { } from './components'

// 引入工具包
import { press, size, ScreenWidth } from '../../util/utils.js'


class OrderList extends Component {
  constructor(props) {
    super(props)
    this.state = {
      refreshing: false,
      payInfo: {
        isPay: false
      },
    }
    this.getOrderList = getOrderList.bind(this)
    this.cancelOrder = cancelOrder.bind(this)
    this.pay = pay.bind(this)
  }

  componentDidMount() {
    const { user, orderList: { nextPage, pageSize } } = this.props
    const loading = Toast.loading('加载中', 0, null, false)
    this.getOrderList({
      pageNum: nextPage,
      pageSize
    }).then(res => {
      Portal.remove(loading)
      this.setState({ refreshing: false });
    }).catch(error => {
      Portal.remove(loading)
    })

    // InteractionManager.runAfterInteractions(() => {
    // ...耗时较长的同步执行的任务...
    // });
  }

  componentWillUnmount() {
    const { dispatch } = this.props
    dispatch({
      type: ActionTypes.orderListReset,
    })
  }

  onRefresh = () => {
    const { orderList: { pageSize } } = this.props
    this.setState({ refreshing: true });
    const loading = Toast.loading('加载中', 0, null, false)
    this.getOrderList({
      pageNum: 1,
      pageSize,
      refresh: true
    }).then(res => {
      Portal.remove(loading)
      this.setState({ refreshing: false });
    }).catch(error => {
      Portal.remove(loading)
    })
  }

  onEndReached = () => {
    const { user, orderList: { nextPage, pageSize, list, total } } = this.props
    if (list.length < total) {
      this.getOrderList({
        pageNum: nextPage,
        pageSize
      })
    }
  }

  getQuantity(orderItemList) {
    let quantity = 0
    orderItemList.map((item, index) => {
      quantity += item.productQuantity
    })
    return quantity
  }

  handleCancelOrder(orderSn, index) {
    const { user, orderList: { nextPage, pageSize } } = this.props
    const loading = Toast.loading('加载中', 0, null, false)
    this.cancelOrder({ orderSn }).then(res => {
      // let order = { ...this.props.orderList }
      // order.list.splice(index, 1)
      // dispatch({
      //   type: ActionTypes.orderList,
      //   data: order
      // })
      Portal.remove(loading)
      Toast.success('删除成功', 2, () => {
        this.onRefresh()
      }, false)
      this.setState({ refreshing: false });
    }).catch(error => {
      console.log(error)
      Portal.remove(loading)
      Toast.fail('删除失败', 2, null, false)
    })
  }

  renderOrderButton(item, index) {
    const { payInfo } = this.state
    if (item.status == 0) {
      // 待付款
      return (
        <View style={{
          flexDirection: 'row',
          justifyContent: 'flex-end',
          alignItems: 'center',
          padding: 10,
          borderTopWidth: .5,
          borderStyle: 'solid',
          borderTopColor: '#e5e5e5',
        }}>
          <TouchableOpacity
            onPress={() => {
              this.pay({
                orderNo: item.orderSn,
                payMode: item.payType
              }).then(res => {
                this.setState({
                  payInfo: {
                    orderNo: item.orderSn,
                    payMode: item.payType,
                    isPay: true,
                  }
                }, () => {
                  Actions.payResults({ html: res.data.data })
                })
              })
            }}
            style={{
              marginLeft: 15,
              width: 100,
              borderWidth: .5,
              borderStyle: 'solid',
              borderColor: '#ddd',
              borderRadius: 6,
              backgroundColor: '#fff',
            }}
          >
            <Text style={{ fontSize: 14, textAlign: 'center', color: '#61676F', lineHeight: 32, }}>现在支付</Text>
          </TouchableOpacity>
          <TouchableOpacity
            onPress={() => {
              Modal.alert('系统提示', '确认删除该订单？', [
                {
                  text: <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>取消</Text>,
                  onPress: () => console.log('cancel'),
                  style: 'cancel',
                },
                {
                  text: <Text style={{ fontSize: 14, color: 'red', lineHeight: 16, }}>确定</Text>,
                  onPress: () => this.handleCancelOrder(item.orderSn, index)
                }
              ])
            }}
            style={{
              marginLeft: 15,
              width: 100,
              borderWidth: .5,
              borderStyle: 'solid',
              borderColor: '#ddd',
              borderRadius: 6,
              backgroundColor: '#fff',
            }}
          >
            <Text style={{ fontSize: 14, textAlign: 'center', color: '#61676F', lineHeight: 32, }}>删除订单</Text>
          </TouchableOpacity>
        </View >
      )
    }
    if (item.status == 1) {
      // 待发货

    }
    if (item.status == 2) {
      // 已发货

    }
    if (item.status == 3) {
      // 已完成

    }
    if (item.status == 4) {
      // 已关闭

    }
    if (item.status == 5) {
      // 无效订单

    }
  }


  render() {
    const { orderList } = this.props
    const { refreshing, payInfo } = this.state
    return (
      <View style={Style.container}>
        <Status />
        <NavBar
          title="我的订单"
          back={true}
        />
        <RnFlatList
          style={{
            backgroundColor: '#f0f2f5'
          }}
          refreshing={refreshing}
          onRefresh={this.onRefresh}
          onEndReached={this.onEndReached}
          removeClippedSubviews={true}
          datas={orderList}
          renderItem={({ item, index }) => {
            return (
              <View style={{
                marginBottom: 10,
                backgroundColor: '#fff'
              }}>
                <View style={{
                  padding: 10,
                  flexDirection: 'row',
                  alignItems: 'flex-start',
                  justifyContent: 'space-between',
                }}>
                  {item.orderType == 0 ? <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>在线</Text> : null}
                  {item.orderType == 1 ? <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>预购订单</Text> : null}
                  {item.orderType == 2 ? <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>书籍代购</Text> : null}
                  {item.orderType == 3 ? <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>杂志代购</Text> : null}
                  {item.status == 0 ? <Text style={{ fontSize: 14, color: '#f23030', lineHeight: 16, }}>待付款</Text> : null}
                  {item.status == 1 ? <Text style={{ fontSize: 14, color: '#f23030', lineHeight: 16, }}>待发货</Text> : null}
                  {item.status == 2 ? <Text style={{ fontSize: 14, color: '#f23030', lineHeight: 16, }}>已发货</Text> : null}
                  {item.status == 3 ? <Text style={{ fontSize: 14, color: '#f23030', lineHeight: 16, }}>已完成</Text> : null}
                  {item.status == 4 ? <Text style={{ fontSize: 14, color: '#f23030', lineHeight: 16, }}>已关闭</Text> : null}
                  {item.status == 5 ? <Text style={{ fontSize: 14, color: '#f23030', lineHeight: 16, }}>删除订单</Text> : null}
                </View>
                <TouchableOpacity
                  onPress={() => {
                    Actions.orderInfo({ id: item.id })
                  }}
                  style={{
                    paddingVertical: 5,
                    backgroundColor: '#f7f7f7'
                  }}
                >
                  {item.orderItemList.map((orderItem, index) => {
                    return (
                      <View style={{
                        flexDirection: 'row',
                        alignItems: 'center',
                        paddingVertical: 5,
                        paddingLeft: 10,
                      }}>
                        <RnImage resizeMode='cover' style={{ backgroundColor: '#ccc', width: 80, height: 80 }} uri={orderItem.productPic} />
                        <View style={{
                          flex: 1,
                          paddingLeft: 10,
                        }}>
                          <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>{orderItem.productName}</Text>
                        </View>
                        <View style={{
                          paddingHorizontal: 10,
                          flexDirection: 'column',
                          alignItems: 'flex-end',
                        }}>
                          <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, marginBottom: 10 }}>RM {orderItem.productPrice}</Text>
                          <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>X {orderItem.productQuantity}</Text>
                        </View>
                      </View>
                    )
                  })}
                </TouchableOpacity>
                <View style={{
                  flexDirection: 'row',
                  justifyContent: 'flex-end',
                  alignItems: 'center',
                  padding: 10

                }}>
                  <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>共 <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>{this.getQuantity(item.orderItemList)}</Text> 件商品  实付款：RM <Text style={{ fontSize: 14, color: '#f23030', lineHeight: 16, }}>{item.totalAmount}</Text></Text>
                </View>
                {this.renderOrderButton(item, index)}
              </View>
            )
          }}
        />
        <IsPay
          payInfo={payInfo}
          onCancel={() => {
            let payInfo = { ...payInfo }
            payInfo.isPay = false
            this.setState({
              payInfo
            })
          }}
        />
      </View >
    );
  }
}


export default connect(({ orderList }) => ({
  orderList,
}))(pureRender(OrderList))
